package cn.slipi.admin.common.interceptor;

import cn.slipi.admin.common.utils.DateUtil;
import cn.slipi.admin.common.utils.NetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lee
 */
@Component
public class GateInterceptor implements HandlerInterceptor {

    private static final Logger LOG = LoggerFactory.getLogger("gateLogger");

    private static final String REQUEST_START_TIME_ATTRIBUTE_KEY = "request_start";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        Long start = System.currentTimeMillis();
        request.setAttribute(REQUEST_START_TIME_ATTRIBUTE_KEY, start);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) {

        Long end = System.currentTimeMillis();
        Long start = (Long) request.getAttribute(REQUEST_START_TIME_ATTRIBUTE_KEY);

        String method = request.getMethod();
        String uri = request.getServletPath();

        String remoteIp = NetUtil.getRequestIp(request);

        // 调用方法的耗时
        long duration = end - start;

        LogBuilder node = LogBuilder.builder();

        node.put("action_time", System.currentTimeMillis());
        node.put("url", method + uri);
        node.put("ip", remoteIp);
        node.put("duration", DateUtil.formatMilliSecond(duration));
        node.put("status", response.getStatus());

        LOG.info(node.build());

    }

}
